package com.eliota.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eliota.common.Constants;
import com.eliota.common.R;
import com.eliota.controller.dto.UserDto;
import com.eliota.entity.User;
import com.eliota.mapper.UserMapper;
import com.eliota.service.UserService;
import com.eliota.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;


/**
 * @author M.G
 * @create 2023-03-17 11:06
 * @date 2023/3/17 11:06
 */

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserMapper userMapper;



    @PostMapping("/login")
    public R login(@RequestBody UserDto userDto) {
        String username = userDto.getUserName();
        String password = userDto.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return R.error(Constants.CODE_400,"参数错误");
        }
        //getone返回的行对象参数
        UserDto dto = userService.login(userDto);
        return R.success(dto,"用户登录成功");
    }

    

    @PostMapping("/register")
    public R register(@RequestBody UserDto userDto){
        String username = userDto.getUserName();
        String password = userDto.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return R.error(Constants.CODE_400,"用户输入无效");
        }
        return R.success(userService.register(userDto));
    }

    /*userNam*/
    @GetMapping("/username/{username}")
    public R findByUserName(@PathVariable String username){
        User byNameUser = userService.getOne(new QueryWrapper<User>().eq("userName", username));
        return R.success(byNameUser);
    }

    @PostMapping("/save")
    public R save(@RequestBody User user){
        user.setStatue(1);
        return R.success(userService.saveOrUpdate(user));
    }

    @GetMapping("/list")
    public R findAll(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("statue",1);
        return R.success(userService.list(queryWrapper));
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id){
        Boolean b = userService.deleteById(id);
        if(b){
            System.out.println(b + ">>>>>>>>>>>>>.删除成功");
            return R.success();
        }else {
            System.out.println("》》》》》》》》》》》》删除失败");
            return R.error("删除失败");
        }
    }

    @PostMapping("/bath/del")
    public R deleteBath(@RequestBody List<Integer> ids){
        return R.success(userService.deleteBatchByIds(ids));
    }

    @GetMapping("/page")
    public R findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam String userName){
        Page<User> userPage = new Page<>(pageNum, pageSize);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
        userQueryWrapper.like("username",userName).orderByDesc("id");
        userQueryWrapper.eq("statue",1);


        /*User currentUser = TokenUtil.getCurrentUser();*/
        return R.success(userService.page(userPage,userQueryWrapper));
    }


    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<User> list = userService.list();
        // 通过工具类创建writer 写出到磁盘路径
        //        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名

        writer.addHeaderAlias("id", "id");
        writer.addHeaderAlias("userName", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");


        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
     * excel
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public R imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        //        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setUserName(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setNikeName(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setPhone(row.get(5).toString());
            users.add(user);
            System.out.println(user.toString());
        }

        userService.saveBatch(users);
        return R.success(true);
    }


}
